#include<iostream>
using namespace std;
#include<string>
#include"Socket.hpp"
#include"protocol.hpp"
#include<time.h>
#include<cstdlib>

void Usage(string proc)
{
    cout << "Usage: " << proc << endl;
}


int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);         
    }

    //
    string serverip = argv[1];
    uint16_t port = stoi(argv[2]);
    
    Socket sockfd;
    sockfd.InitSocket();
    bool r = sockfd.Connect(serverip, port);
    if (!r) return 1;

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    string opers = "+-*/%";
    
    

    string inbuffer_stream;
    while (cnt <= 1)
    {
        cout << "第" << cnt++ << "次测试......" << endl;
        int x = rand() % 100 + 1;
        usleep(1234);   

        int y = rand() % 100 ;
        usleep(4321);

        char oper = opers[rand() % opers.size()];   
        Request req(x, y, oper);

        req.DebugPrint();

        string package;
        req.Serialize(&package);
        
        package = Encode(package);
        cout << "这是最新的发出去的请求:\n" << package;
        write(sockfd.Fd(), package.c_str(), package.size());

        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));  //我们也无法保证我们能够读到一个完整的报文
        if (n > 0)
        {
            buffer[n] = 0;
            inbuffer_stream += buffer;   
            string content;

            bool r = Decode(inbuffer_stream, &content);  //result code

            Response resp;
            r = resp.DeSerialize(content);            

            resp.DebugPrint();
        }

        sleep(1);

    }

    return 0;
}